import {useEffect} from "react";
import {theme} from "antd";
import {RootState, useSelector} from "@/store/index.ts";
import {setStyleProperty} from "@/utils/index.ts";
import {getLightColor, getDarkColor} from "@/utils/color.ts";
import siderTheme from "@/style/theme/sider";
import headerTheme from "@/style/theme/header";
import globalTheme from "@/style/theme/global";

type ThemeType = "light" | "dark";

const useTheme = () => {
    const {token} = theme.useToken();

    const {
        isDark,
        primary,
        borderRadius,
        compactAlgorithm
    } = useSelector((state: RootState) => state.globalSlice);

    //切换夜间模式
    useEffect(() => switchDark(), [isDark]);
    const switchDark = () => {
        const html = document.documentElement;
        html.setAttribute("class", isDark ? "dark" : "");
        changePrimary();
    };

    //切换主题色
    useEffect(() => changePrimary(), [primary, borderRadius, compactAlgorithm]);
    const changePrimary = () => {
        const type: ThemeType = isDark ? "dark" : "light";

        Object.entries(globalTheme[type]).forEach(([key, val]) => setStyleProperty(key, val));

        Object.entries(token).forEach(([key, val]) => setStyleProperty(`--hooks-${key}`, val));

        for (let i = 1; i <= 9; i++) {
            setStyleProperty(
                `--hooks-colorPrimary${i}`,
                isDark ? `${getDarkColor(primary, i / 10)}` : `${getLightColor(primary, i / 10)}`
            );
        }
    };

    //切换侧边栏主题色
    useEffect(() => changeSiderTheme(), [isDark]);
    const changeSiderTheme = () => {
        const type: ThemeType = isDark ? "dark" : "light";
        Object.entries(siderTheme[type]).forEach(([key, val]) => setStyleProperty(key, val));
    };


    //切换header背景主题色
    useEffect(() => changeHeaderTheme(), [isDark]);
    const changeHeaderTheme = () => {
        const type: ThemeType = isDark ? "dark" : "light";
        Object.entries(headerTheme[type]).forEach(([key, val]) => setStyleProperty(key, val));
    };
};

export default useTheme;
